package models
/*********************************************************/
/********************本文档为数据库结构文档******************/
/**************RemoteWareHouse的数据结构********************/
/*********************version:1.0*************************/
/****Copyright (c) 2014年 许剑华. All rights reserved******/
/*********************************************************///控制码字相关的结构体
import (
	//"errors"
	_"log"
	_"github.com/astaxie/beego/validation"
	//."smart_home/lib"
	"github.com/astaxie/beego/orm"
	"fmt"
	"os"
	"time"
	//"strconv"
)
type NewVersionApp struct {
	Id 					int		`orm:"unique;auto;pk"`
	AppName				string
	Version				string
	UpdateInfo			string
	UpdateTime			time.Time
	URL					string
}


func init() {
	// 需要在init中注册定义的model
	orm.RegisterModel(new(NewVersionApp))
}
func AddNewVersion(app_name string,version string,update_info string,url string) (err error) {
	file := NewVersionApp{AppName:app_name,Version:version,UpdateInfo:update_info,UpdateTime:time.Now(),URL:url}
	o := orm.NewOrm()

		_, err = o.Insert(&file)
		if err != nil{
			fmt.Println("err",err)

		}

	return  err
}


func GetLastVersion()(NewVersionApp,int,error){
	o := orm.NewOrm()
	new_version := new(NewVersionApp)
	var new_versions []NewVersionApp
	qs := o.QueryTable(new_version)
	qs = qs.OrderBy("-update_time")
	count,err := qs.All(&new_versions)
	fmt.Println("count",count)
	fmt.Println("err",err)

	fmt.Println("new_versions",new_versions)
	if count > 0 {
		//new_versions[0].URL = "http://localhost:8080/api/download_app/"+strconv.FormatInt(int64(new_versions[0].Id),10)
		return new_versions[0],1,nil
	}
	//      fmt.Println("count",count)
	//      fmt.Println("files",files)
	return NewVersionApp{}, 0,err
}
func DeleteById(id int)(error){
	new_version := NewVersionApp{Id: id}
	o := orm.NewOrm()
	err := o.Read(&new_version, "Id")
	if err == orm.ErrNoRows {
		//		fmt.Println("查询不到")
		return err
	} else if err == orm.ErrMissPK {
		//		fmt.Println("找不到主键")
		return err
	}else if err == nil{
		_,err = o.Delete(&new_version)
		if err == nil{
			err = os.Remove(new_version.URL)
		}else{
			_, err = o.Insert(&new_version)  //如果删除失败，则重新写回
		}
	}
	//	fmt.Println("找到数据：",user)
	return err
}
func GetVersionList()([]NewVersionApp,int64,error){
	o := orm.NewOrm()
	new_version := new(NewVersionApp)
	var new_versions []NewVersionApp
	qs := o.QueryTable(new_version)
	qs = qs.OrderBy("-update_time")
	count,err := qs.All(&new_versions)
	fmt.Println("count",count)
	fmt.Println("err",err)

	fmt.Println("new_versions",new_versions)

	//      fmt.Println("count",count)
	//      fmt.Println("files",files)
	return new_versions, count,err
}
